package novel.front.novellist.controller;

import novel.common.constant.IConstInfo;
import novel.common.utils.FtpUtils;
import novel.common.utils.qiniu.UploadFactory;
import novel.common.utils.qiniu.UploadUtilImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sutong on 2017/10/16.
 */
@Controller
@RequestMapping("uploadFile")
public class UploadFileController {

    protected static Logger logger = LoggerFactory.getLogger(UploadFileController.class);

    //ftp上传
    @ResponseBody
    @RequestMapping(value = "upPhotoFtp", method = RequestMethod.POST)
    public Map<String, String> upPhotoFtp(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = processUploadPostFtp(file, request);
        return map;
    }

    public Map<String, String> processUploadPostFtp(MultipartFile file, HttpServletRequest request) {
        String fileUrl = "";
        Map<String, String> map = new HashMap<String, String>();
        // 判断提交的请求是否包含文件
        try {
            // 上传文件的返回地址
//            String targPath = "www.kukuwu.com";
            String targPath = "http://localhost:8088";

            if (file != null) {
                //获取file的名字
                String fileClientName = file.getOriginalFilename();
                String fileSuffix = fileClientName.substring(fileClientName.lastIndexOf("."), fileClientName.length());
                if (!isPhotoFormat(fileSuffix)) {
                    logger.error("上传文件的格式错误=" + fileSuffix);
                    map.put("status", "error");
                    map.put("message", "格式错误，仅支持jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps格式'");
                    return map;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("开始上传文件:" + file.getName());
                }

                String fileServerName = generateFileName(file, fileSuffix);

                //MultipartFile转file
                File f = null;
                if(file.equals("")||file.getSize()<=0){
                    file = null;
                }else{
                    InputStream ins = file.getInputStream();
                    f=new File(fileClientName);
                    inputStreamToFile(ins, f);
                }

                //生成所要存的文件夹名
                String dirName = generateDirName();
                FtpUtils ft = new FtpUtils("47.94.255.148", 21, "ftpuser",  "Aasgt583");
                if(ft.open()) {
                    //上传
                    boolean res =  ft.upload(new FileInputStream(f), fileServerName, dirName);
                    System.out.println("上传返回结果"+res);
                }

                //程序结束时，删除临时文件
                deleteFile(f);

                // 组装返回url，以便于ckeditor定位图片
                fileUrl = targPath + dirName + fileServerName;
                map.put("status", "success");
                map.put("message", "上传成功");
                map.put("fileServerName",dirName+fileServerName);
                map.put("url", fileUrl);
                System.out.println("成功");
            } else {
                map.put("status", "error");
                map.put("message", "文件为空");
            }


        } catch (IOException e) {
            logger.error("上传文件发生异常！", e);
            map.put("status", "error");
            map.put("message", "上传文件发生异常！");
        } catch (Exception e) {
            logger.error("上传文件发生异常！", e);
            map.put("status", "error");
            map.put("message", "上传文件发生异常！");
        }

        return map;
    }

    public void inputStreamToFile(InputStream ins,File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 本地上传
     * @param file
     * @param request
     * @param response
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "upPhoto", method = RequestMethod.POST)
//    public Map<String, String> processUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
//        Map<String, String> map = processUploadPost(file, request);
//        return map;
//    }
//
//    public Map<String, String> processUploadPost(MultipartFile file, HttpServletRequest request) {
//        String fileUrl = "";
//        Map<String, String> map = new HashMap<String, String>();
//        // 判断提交的请求是否包含文件
//        try {
//            //生成所要存的文件夹名
//            String dirName = generateDirName();
//            // 上传文件的返回地址
//            String targPath = request.getSession().getServletContext().getRealPath(dirName);
//            File dir = new File(targPath);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            if (file != null) {
//                //获取file的名字
//                String fileClientName = file.getOriginalFilename();
//                String fileSuffix = fileClientName.substring(fileClientName.lastIndexOf("."), fileClientName.length());
//                if (!isPhotoFormat(fileSuffix)) {
//                    logger.error("上传文件的格式错误=" + fileSuffix);
//                    map.put("status", "error");
//                    map.put("message", "格式错误，仅支持jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps格式'");
//                    return map;
//                }
//
//                if (logger.isInfoEnabled()) {
//                    logger.info("开始上传文件:" + file.getName());
//                }
//
//                String fileServerName = generateFileName(file, fileSuffix);
//                // 为了客户端已经设置好了图片名称在服务器继续能够明确识别，这里不改名称
//                File tempFile = new File(targPath + "/" + fileServerName);
//                //文件转换
//                file.transferTo(tempFile);
//                if (logger.isInfoEnabled()) {
//                    logger.info("上传文件结束，新名称:" + fileServerName + ".floder:"
//                            + tempFile.getPath());
//                }
//
//                // 组装返回url，以便于ckeditor定位图片
//                fileUrl = targPath + "/" + fileServerName;
//                map.put("status", "success");
//                map.put("message", "上传成功");
//                map.put("fileServerName",dirName+fileServerName);
//                map.put("url", fileUrl);
//                System.out.println("成功");
//            } else {
//                map.put("status", "error");
//                map.put("message", "文件为空");
//            }
//
//
//        } catch (IOException e) {
//            logger.error("上传文件发生异常！", e);
//            map.put("status", "error");
//            map.put("message", "上传文件发生异常！");
//        } catch (Exception e) {
//            logger.error("上传文件发生异常！", e);
//            map.put("status", "error");
//            map.put("message", "上传文件发生异常！");
//        }
//
//        return map;
//    }

    /**
     * 七牛云上传
     * @param file
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "upPhoto", method = RequestMethod.POST)
    public Map<String, String> processUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = processUploadPost(file, request);
        return map;
    }

    public Map<String, String> processUploadPost(MultipartFile file, HttpServletRequest request) {
        String fileUrl = "";
        Map<String, String> map = new HashMap<String, String>();
        // 判断提交的请求是否包含文件
        try {
            if (file != null) {
                //获取file的名字
                String fileClientName = file.getOriginalFilename();
                String fileSuffix = fileClientName.substring(fileClientName.lastIndexOf("."), fileClientName.length());
                if (!isPhotoFormat(fileSuffix)) {
                    logger.error("上传文件的格式错误=" + fileSuffix);
                    map.put("status", "error");
                    map.put("message", "格式错误，仅支持jpg|jpeg|bmp|gif|png格式'");
                    return map;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("开始上传文件:" + file.getName());
                }

                String fileServerName = uploadImage(file);

                // 组装返回url，以便于ckeditor定位图片
                map.put("status", "success");
                map.put("message", "上传成功");
                map.put("fileServerName",fileServerName);
                map.put("url", fileServerName);
                System.out.println("成功");
            } else {
                map.put("status", "error");
                map.put("message", "文件为空");
            }


        } catch (IOException e) {
            logger.error("上传文件发生异常！", e);
            map.put("status", "error");
            map.put("message", "上传文件发生异常！");
        } catch (Exception e) {
            logger.error("上传文件发生异常！", e);
            map.put("status", "error");
            map.put("message", "上传文件发生异常！");
        }

        return map;
    }

    public String uploadImage(MultipartFile image) throws Exception {
        UploadUtilImpl uploadUtil = UploadFactory.createUpload(IConstInfo.accesskey, IConstInfo.secretKey,
                IConstInfo.bucketHostName, IConstInfo.bucketName);
        return uploadUtil.uploadFile("/filePath/", image);
    }

    private String generateFileName(MultipartFile folder, String suffix) {
        String filename;
        File file;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        String base = format.format(date);
        filename = base + suffix;
        file = new File(filename);
        int i = 1;
        while (file.exists()) {
            filename = String.format("%s_%d.%s", base, i, suffix);
            i++;
        }
        return filename;
    }

    private String generateDirName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String base = format.format(date);
        return "/static/images/" + base + "/";
    }

    public static Boolean isPhotoFormat(String fileSuffix) {
        if (StringUtils.equalsIgnoreCase(fileSuffix, "jpg")
                && !StringUtils.equalsIgnoreCase(fileSuffix, "jpeg")
                && !StringUtils.equalsIgnoreCase(fileSuffix, "bmp")
                && !StringUtils.equalsIgnoreCase(fileSuffix, "gif")
                && !StringUtils.equalsIgnoreCase(fileSuffix, "png")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "txt")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "doc")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "docx")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "xls")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "xlsx")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "csv")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "ppt")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "pptx")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "pdf")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "wps")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "et")
//                && !StringUtils.equalsIgnoreCase(fileSuffix, "dps")
                )
            return false;
        return true;
    }
}
